//
//  FTValueHolder.m
//  WebPDA
//
//  Created by Justin Yip on 8/24/10.
//  Copyright 2010 TenNights.com. All rights reserved.
//

#import "FTValueHolder.h"
#import <CoreData/CoreData.h>


@implementation FTValueHolder
@synthesize entity;
@synthesize dictionary;

-(id)init {
	if ((self = [super init])) {
		dictionary = [[NSMutableDictionary alloc] init];
	}
	return self;
}

#pragma mark -
#pragma mark KVC support

-(BOOL)containsValueForKey:(NSString *)key {
	SEL getter = NSSelectorFromString(key);
	//check if the entity has a getter for the property(key), or the dictionary contains key-value pair for the key
	if ([entity respondsToSelector:getter] || [dictionary objectForKey:key]) {
		return YES;
	}else {
		return NO;
	}
}

-(id)valueForKey:(NSString *)key {
	if (nil != entity && [entity respondsToSelector:NSSelectorFromString(key)]) {
		return [entity valueForKey:key];
	}else {
		return [dictionary valueForKey:key];
	}
	return [super valueForKey:key];
}

-(void)setValue:(id)value forKey:(NSString *)key {
//	if (locked) { return; }
	
	//1.
	[dictionary setValue:value forKey:key];
	//2.
	if (nil != entity) {
		//setXxx
		NSString *selectorString = [NSString stringWithFormat:@"set%@:", [key capitalizedString]];
		SEL selector = NSSelectorFromString(selectorString);
		if ([entity respondsToSelector:selector]) {
			[entity performSelector:selector withObject:value];
		}
	}
}

-(id)entityWithApplyData {
	// TODO: apply data from dictionary to entity here
	return entity;
}

#pragma mark -
#pragma mark Memory Management

-(void)dealloc {
	[entity release];
	[dictionary release];
	[super dealloc];
}
@end
